const app = getApp()
const api = require('../config/api.js');
const util = require('util.js'); 
const signalR2 = require('signalR2.js'); 
const log = require('../utils/log.js'); 

function initConnection() {
  log.info("初始化连接");
  app.connection = new signalR2.signalR(); 
  //接收
 
  app.connection.on("receive", function (message) {
      //必须收到回复才算连接成功
      try
      {
           
          
          if (message === '') {
              return;
          } 
          //处理自己的消息 
          let mess = JSON.parse(message);
          console.log("收到回复-->"+message); 

        if (app.PageName.toUpperCase() === 'SCANINYARD') {
            //扫码进出
            if (mess.Header.Station_Id === app.StationId && mess.Header.Station_No === app.StationNo
                && mess.Header.Client_No === app.OpenId && mess.Header.Client_Type === app.BrowserType) {
                if (mess.Header.messageType === 1 || mess.Header.messageType === 2 || mess.Header.messageType === 3) {
                    log.info(mess);
                    util.tryHideFullScreenLoading(true); 
                    if (mess.Footer.Result == 1) {
                        //扫码成功
                        app.OpenGateStatus = true;//已经收到消息 
                        
                        util.showErrorToast(mess.Footer.Error,999999); 
                    }
                    else if (mess.Footer.Result == 2) {
                        //扫码失败
                        app.OpenGateStatus = true;//已经收到消息 
                        util.showErrorToast(mess.Footer.Error,999999);
                    }
                }
            }
        }
        else if(app.PageName.toUpperCase() === 'COUPON')
        {
            if (mess.Header.Client_No === app.OpenId && mess.Header.Client_Type === app.BrowserType
                && (mess.Header.messageType === 11 || mess.Header.messageType === 12 || mess.Header.messageType === 13)) {
                if (mess.Footer.Result === 2) {
                    util.showErrorToast(mess.Footer.Error,10000);  
                }
                else { 
                    util.showFullScreenLoading('领券中...');
                    //准备跳转页面
                    setTimeout(function () {
                        let body = {
                            "OpenId": app.OpenId,
                            "SaleId": app.SaleId
                        };
                        SendMessage(14/*MessageType.获取停车券*/, body, 0, "");//获取停车券
                    }, 2000);
                }
            }
            else if (mess.Header.Client_No === app.OpenId && mess.Header.Client_Type === app.BrowserType && mess.Header.messageType === 14) {

                if (mess.Body != null) {
                    //跳转页面
                     app.curthis.showyhq(); 
                }
                else {
                    util.showErrorToast("领取失败，可能原因：1、商户券不够；2、您的车辆未入场；3、客户端未在线；4、网络延时原因",15000); 
                }
                
            }
        }
        else if(app.PageName.toUpperCase() === 'CARQUERY' || app.PageName.toUpperCase() === 'SCANOUTYARD')
        {
            if (mess.Header.Client_No == app.OpenId && mess.Header.Client_Type == app.BrowserType && mess.Header.messageType == 14) {
                //显示可用券张数

                app.curthis.setData({YHQ: 0})
                if (mess.Body != null) {
                    app.ParkingTitckets = mess.Body; 
                    let c = app.ParkingTitckets.filter(o=> o.ID>0).length;
                    app.curthis.setData({YHQ: c})
                    app.curthis.setData({coupon: app.ParkingTitckets})
                }
            }
            else if (mess.Header.Client_No == app.OpenId && mess.Header.Client_Type == app.BrowserType && (mess.Header.messageType == 4
                || mess.Header.messageType == 5 || mess.Header.messageType == 6 || mess.Header.messageType == 9)) {
                
                if (mess.Header.messageType == 6 || mess.Header.messageType == 4) {
                    //请求获取场所编号  
                    log.info(mess);
                    util.tryHideFullScreenLoading(true);
                    if ((mess.Footer.Result == 1 || mess.Footer.Result == 0)) {
                        
                        if (mess.Body.length > 1) {
                            //这里是存在多条记录，需要做选择哦。
                            app.startPay = false;
                            util.showErrorToast('查询费用错误，请到出口处扫码交费！',999999);  
                            return;
                        }
                        if (mess.Body[0].titckets == null && mess.Body[0].PlateNo != "") {
                            app.startPay = false;
                            app.curPlateNo = mess.Body[0].PlateNo;
                            app.curPayCardTypeId = mess.Body[0].PayCardTypeId;
                            app.curPlateColor = mess.Body[0].PlateColor;
                            app.StationId = mess.Body[0].StationId;
                            app.StationNo = mess.Body[0].StationNo;
                            app.StationName = mess.Body[0].StationName; 
                            if (app.curPlateNo != "" && mess.Body[0].OpenId != "") {
                                //出口支付，切换界面
                                if (app.curPlateNo === "无") { 
                                    app.curthis.setType(2) ;
                                    return;
                                }
                                else {
                                    app.curthis.setHistory(app.curPlateNo);
                                } 
                            }
                        }
                        else if (mess.Body[0].titckets != null && mess.Body[0].carIN.PlateNo != "") {
                            app.startPay = false; 
                            app.curPlateNo = mess.Body[0].carIN.PlateNo;
                            app.curPayCardTypeId = mess.Body[0].carIN.PayCardTypeId;
                            app.curPlateColor = mess.Body[0].carIN.PlateColor;
                            app.StationId = mess.Body[0].carIN.StationId;
                            app.StationNo = mess.Body[0].carIN.StationNo;
                            app.StationName = mess.Body[0].carIN.StationName;
                            app.ParkingTitckets = mess.Body[0].titckets;
                            //显示可用券张数
                            app.curthis.setData({YHQ:0})
                            if(app.ParkingTitckets!=null)
                            { 
                                let c = app.ParkingTitckets.filter(o=> o.ID>0 ).length;
                                app.curthis.setData({YHQ: c})
                                app.curthis.setData({coupon: app.ParkingTitckets})
                            } 
                            if (app.curPlateNo != "" && mess.Body[0].carIN.OpenId != "") {
                                //出口支付，切换界面
                                if (app.curPlateNo === "无") { 
                                    app.curthis.setType(2) ;
                                    return;}
                                else {
                                    app.curthis.setHistory(app.curPlateNo);
                                }
                            }
                        }
                    }
                    else if (mess.Footer.Result == 2 && mess.Header.messageType == 6) {
                        app.startPay = false; 
                        //收到失败消息 
                        if (mess.Body[0].OpenId != "" && app.curthis.data.nums.length === 1) {

                        }
                        else {
                            if(app.fromOutGate==="Y"){util.showErrorToast('当前车辆未入场，请更换车牌重试！',999999);  return;}
                            app.curthis.setData({
                                   isShow:false,
                                   isPop:true,
                                   errinfor: '当前车辆未入场，请更换车牌重试！'
                            }); 
                        } 
                    }
                    //原封不动的消息不处理
                }
                else if (mess.Header.messageType == 5) {
                    log.info(mess);
                    util.tryHideFullScreenLoading(true);
                    app.startPay = false;
                    app.hadGateRecvice = true; 
                    if (mess.Footer.Result == 1) {
                        //alert("OK啦，好开森");
                        if (mess.Body.YS == 0 && mess.Body.SS == 0 && mess.Body.MD == 0) {
                            
                            if(app.fromOutGate==="Y"){util.showErrorToast('未到交费时间或您当前无需交费！！',999999);  return;}
                            let stopTime ='';
                            try{
                                stopTime = '您已经停车【'+mess.Body.StopTime+'】 当前无需交费';
                            }
                            catch(ex){ 
                            }
                            if(stopTime==''){
                                stopTime = '未到交费时间或您当前无需交费！';
                            }
                            app.curthis.setData({
                                isShow:false,
                                isPop:true,
                                errinfor: stopTime
                            });  
                        }
                        else {

                            //算费成功，需要初始化页面
                            app.curthis.setData({curShow:3,isShow: false});
                            app.curPlateNo = mess.Body.CardNo;
                            app.curPayCardTypeId = mess.Body.PayCardTypeId;
                            app.curPlateColor = mess.Body.PlateColor;
                            app.payPlateNo = mess.Body.CardNo;
                            let YS = mess.Body.YS;
                            app.payYS = YS;
                            app.paySS = mess.Body.SS;
                            app.payMD = mess.Body.MD;
                            app.OverTime = mess.Body.OverTime;
                            let StationName = mess.Body.StationName;
                            app.payStationId = mess.Body.StationId;
                            app.payINTime = mess.Body.INTime;
                            app.payStopTime = mess.Body.StopTime;
                            app.payPaysource = mess.Body.paysource;
                            app.payRecordId = mess.Body.RecordId;
                            app.payOpenId = mess.Body.OpenId;
                            app.payEndTime = mess.Body.OUTTime.toString().replace(/-/g, "").replace(/:/g, "").replace(/ /g, "");
                            app.payOrderTime = mess.Body.PayOrderTime.toString().replace(/-/g, "").replace(/:/g, "").replace(/ /g, "");
                            app.CDMD = mess.Body.CDMD;
                            app.HYMD = mess.Body.HYMD;
                            app.LocalMD = (mess.Body.MDQC==null?0:(mess.Body.MDQC/100));
                            let cdsj ='';
                            let hysj ='';
                            if (app.CDMD > 0) {
                                let r = util.Second2String(app.CDMD);
                                if (r != "") {
                                    //显示充电免单时间
                                    cdsj = r;
                                }
                            }
                            if (app.HYMD > 0) {
                                let r = util.Second2String(app.HYMD);
                                if (r != "") {
                                    //显示会员免单时间
                                    hysj = r;
                                } 
                            }
                            app.HYMDSJ = hysj;
                            app.CDMDSJ = cdsj;
                            let ShowVIPReg = false;
                            if(app.VipParams!=null && app.NewVip==null && app.HYMD<=0){
                                ShowVIPReg = true;
                            }
                             
                            
                            app.curthis.setData({
                                CP: app.curPlateNo,
                                RCSJ: app.payINTime,
                                TCSJ: app.payStopTime, 
                                HYMD: app.HYMD,
                                CDMD: app.CDMD,
                                HYMDSJ: hysj,
                                CDMDSJ: cdsj, 
                                SYJF: 0,
                                LocalMD: app.LocalMD,
                                PaySS: app.paySS,
                                PayYF: app.paySS,
                                YS: YS,  
                                CSSJ: app.OverTime,
                                num: 0,
                                isSwitch: false, 
                                StationName: app.StationName,
                                isVipUser: (app.NewVip!=null),
                                ShowVIPReg: ShowVIPReg
                            })
                            if (mess.Body.FromOutGate === null || mess.Body.FromOutGate === 'undefined') {
                                app.fromOutGate = "N"
                            }
                            else {
                                if (mess.Body.FromOutGate.toString() != "Y" && mess.Body.FromOutGate.toString() != "N") {
                                    try {
                                        let ll = mess.Body.FromOutGate.toString().split(',');
                                        app.BillNo = ll[0];
                                        app.SaleId = ll[1];
                                        app.fromOutGate = "Y";
                                    }
                                    catch (ex) {
                                        util.showErrorToast('算费发生错误，请扫通道码进行缴费！',999999);   
                                        return;
                                    } 
                                }
                                else {
                                    app.fromOutGate = mess.Body.FromOutGate.toString();
                                }
                            }
                            if(app.fromOutGate=="Y" && app.LocalMD>0)
                            {
                                util.request2(api.isExistsFrozenParkingTitckets, {   
                                    StationId: app.StationId,
                                    IN_ID: app.payRecordId, 
                                  }, 'POST').then(function(res){
                                        if (res=="True") {    
                                            app.curthis.setData({BDMDBT:'优惠券(已用)'});
                                        }  
                                        else {   
                                            app.curthis.setData({BDMDBT:'本地免单'}); 
                                        }
                                    },
                                    function(errmsg){  
                                        app.curthis.setData({BDMDBT:'本地免单'}); 
                                    }
                                  ); 
                            }
                            //算费成功，需要初始化页面
                            /*VIP积分由前端操作完成 BEGIN*/  
                            app.VipUseSoc = "N" 
                            /*VIP积分由前端操作完成 END*/
                            
                            //免单券可以点 
                            app.curthis.setData({ 
                                    DJS: 90,
                            });
                            app.canClickticket = true;
                            if(app.PageName.toUpperCase() === 'CARQUERY' || app.PageName.toUpperCase() === 'SCANOUTYARD')
                            {
                                if(app.inter==null)
                                {
                                    app.inter = setInterval(function() {
                                    app.curthis.setData({ 
                                        DJS: app.curthis.data.DJS - 1,
                                    });
                                    if (app.curthis.data.DJS < 0) {
                                        clearInterval(app.inter)
                                        app.inter = null;
                                        app.curthis.setData({ 
                                            DJS: 90
                                        });
                                        app.curthis.setData({curShow:1})
                                    }
                                    }, 1000); 
                                }
                            }
                        }
                    }
                    else {
                        let message = mess.Footer.Error;
                        if (message == "本地已经使用优免不允许再使用优免券") {
                            app.selectBillNos = [];
                            //新建停车券
                            app.curthis.setData({
                                isShow:false,
                                isPop:true,
                                errinfor: message
                            });    
                            //初始化界面
                            //免单券可以点
                            app.canClickticket = true;
                            return;
                        }
                        if (app.OpenId.startsWith("*") && app.OpenId.endsWith("*")) {
                            if(app.fromOutGate==="Y"){util.showErrorToast(message,999999);  return;} 
                            app.curthis.setData({
                                isShow:false,
                                isPop:true,
                                errinfor: message
                            });   
                            //初始化界面
                        }
                        else {
                            if (mess.Footer.Error == "车辆未进场" && mess.Body[0].OpenId != "") {
                                return;
                            }
                            if(app.fromOutGate==="Y"){util.showErrorToast(message,999999);  return;}
                            app.curthis.setData({
                                isShow:false,
                                isPop:true,
                                errinfor: message
                            });   
                        }
                    }

                }
                else if (mess.Header.messageType == 9) {
                    log.info(mess);
                    util.tryHideFullScreenLoading(true);
                    app.hadGateRecvice = true;
                    util.showErrorToast('谢谢您的光临，欢迎下次再来！',999999,'提示');     
                }

            }
        }
     }
     catch(err)
     {
        console.error("回复错误-->"+err);
        log.error("回复错误-->"+err);
     }
  });
  app.connection.on("connection", function () {
        //消息格式
         
        let body = {
            "PorgramVersion": "PV1.0",
            "DataBaseVersion": "",
            "Id": 0,
            "PassId": 0,
            "PassIndex": 0,
            "Video_Ip": "",
            "Video_Status": "",
            "Display_Ip": "",
            "Display_Status": ""
        }
        SendMessage(0/*MessageType.心跳包*/, body, 0, "");//心跳包 
  });
}

function SendMessage(messageType, body, result, error) { 
  let messageHeard = {
      "Station_Id": app.StationId,
      "Station_No": app.StationNo,
      "Station_Name": app.StationName,
      "Client_Type": app.BrowserType,
      "Client_No": app.OpenId,
      "messageType": messageType
  };
  let messageFooter = {
      "Result": result,
      "Error": error
  }
  let MessageBoday = {
      "Header": messageHeard,
      "Body": body,
      "Footer": messageFooter
  }
  const objToStr = JSON.stringify(MessageBoday);
  
  if(app.connection && app.connection.IsConnectioned())
  {
      console.log("准备发送-->"+objToStr); 
      app.connection.sendMessage(objToStr);
  }
}
//查询收费
function startPayNormal() { 
  console.log("准备连接服务-->"+api.ApiChatUrl);
  log.info("准备连接服务-->"+api.ApiChatUrl);
 
  log.info("准备打开连接Hub2");
  try { 
            app.startConnectedTime = new Date();
            setTimeout(() => { 
                if(!app.connection || !app.connection.IsConnectioned())
                {
                    let now = new Date();
                    var timeSpan = Math.abs(now - app.startConnectedTime);
                    if(timeSpan>9000)
                    {
                        util.tryHideFullScreenLoading(true);
                        util.showErrorToast('对不起！打开连接超时，请重新扫码',999999);
                        return;
                    }
                }
            }, 10000);
            if(!app.connection || !app.connection.IsConnectioned())
            { 
                initConnection();
                app.connection.connection(api.ApiChatUrl+"/AiYardChat");
            }
            log.info("已经打开连接Hub2");
            //五秒一次的心跳包
            if(app.interval==null)
            {
                app.interval = setInterval(function () {
                    
                    let body = {
                        "PorgramVersion": "PV1.0",
                        "DataBaseVersion": "",
                        "Id": 0,
                        "PassId": 0,
                        "PassIndex": 0,
                        "Video_Ip": "",
                        "Video_Status": "",
                        "Display_Ip": "",
                        "Display_Status": ""
                    }
                    try
                    { 
                        if(!app.connection || !app.connection.IsConnectioned())
                        {
                            console.log("掉线了，准备重新发起连接......");
                            app.connection.connection(api.ApiChatUrl+"/AiYardChat");
                        }
                    }
                    catch(err)
                    {}
                    SendMessage(0/*MessageType.心跳包*/, body, 0, "");//心跳包
                }, 5000); 
            }
  } catch (err) {
      console.log("连接服务器错误"+err);
      log.info("连接服务器错误"+err);
      setTimeout(() => startPayNormal(), 1000);
  }
  
};
//请求开闸
function startOpenGate() { 
    console.log("准备连接服务-->"+api.ApiChatUrl);
    log.info("准备连接服务-->"+api.ApiChatUrl);
    
    log.info("准备打开连接Hub2");
    try {
         
        util.showFullScreenLoading('请求通行中......');
        app.startConnectedTime = new Date();
        
        app.OpenGateStatus = false;
        app.OpenGateTime = new Date();
        let startOpenGete = new Date();
        setTimeout(() => { 
            if (!app.OpenGateStatus) {
                let now = new Date(); 
                let spanTime = now.getTime() - startOpenGete.getTime(); 
                if (spanTime >= 10000) {
                    util.tryHideFullScreenLoading(true);
                    util.showErrorToast('对不起！请求通行超时，请重新扫码',999999);
                }
            } 
        }, 11000);
        if(!app.connection || !app.connection.IsConnectioned())
        {
            initConnection();
            app.connection.connection(api.ApiChatUrl+"/AiYardChat");
        }
        if(app.interreq==null)
        {
            app.interreq = setInterval(function () {
                if(app.connection && app.connection.IsConnectioned())
                {
                    let YardClientId = parseInt(app.BillNo, 10); 
                    let pS = app.SaleId.split('*')[0];
                    let pL = app.SaleId.split('*')[1];
                    let PassId = parseInt(pS, 10);
                    let PassIndex = parseInt(pL, 10);
                    let body = {
                        "YardClientId": YardClientId,
                        "PassId": PassId,
                        "PassIndex": PassIndex
                    }
                    clearInterval(app.interreq);
                    app.interreq = null;
                    SendMessage(3/*MessageType.扫码进出*/, body, 0, "");//扫码进出 
                    return;
                }
            }, 500);
        }
         
    } catch (err) {
        //扫码失败
        console.log("扫码失败"+err);
        log.info("扫码失败"+err);
    }
};
//请求算费代码部分
/*请求获取StationId */
function GetSationId(inputTxt, messageType, ifreeType, ifreeValue, iPayEndTime,iFromOutGate) {
     
    if (!app.startPay) {
        app.beginPayTime = new Date();
        let startPayTime = new Date();
        util.showFullScreenLoading('请求算费中......');
        setTimeout(() => {  
                let now = new Date();  
                let spanTime = now.getTime() - startPayTime.getTime(); 
                if (spanTime >= 5000 && app.startPay) {
                    util.tryHideFullScreenLoading(true);
                    app.startPay = false;
                    if(!app.hadGateRecvice)
                    {
                        if(app.fromOutGate==="Y" )
                        {
                            util.showErrorToast('对不起！请求算费超时，重新扫码！',999999);
                        }
                        else
                        {
                            util.showErrorToast('对不起！请求算费超时，请重试！');
                        }
                    }
                } 
        }, 6000);
        app.startPay = true;
        let iPlateNo = inputTxt;
        if (iPlateNo == "") {
            iPlateNo = app.curPlateNo;
        }
        let iPlateColor = 1;
        if (app.curPlateColor != iPlateColor) {
            iPlateColor = app.curPlateColor;
        }
        let iOpenId = app.OpenId;
        let iClientType = app.BrowserType;
        let iPayCardTypeId = 0;
        if (app.curPayCardTypeId > 0) {
            iPayCardTypeId = app.curPayCardTypeId;
        }

        //&& app.PageName.toUpperCase()==="SCANOUTYARD" 
        if (iFromOutGate == "Y" ) {
            let YardClientId = parseInt(app.BillNo, 10);
            let PassId = parseInt(app.SaleId, 10);
            iPlateNo = YardClientId.toString();
            iPlateColor = PassId.toString();
        }
        let vipCode = "";
        if(app.NewVip!=null)
        {
           vipCode = app.NewVip.member_code;
        }
        let body = [{
            "StationId": app.StationId,
            "StationNo": app.StationNo,
            "StationName": app.StationName,
            "PlateNo": iPlateNo,
            "PayCardTypeId": iPayCardTypeId,
            "PlateColor": iPlateColor,
            "OpenId": iOpenId,
            "ClientType": iClientType,
            "TenantId": app.TenantId,
            "freeType": ifreeType,
            "freeValue": ifreeValue,
            "PayEndTime": iPayEndTime,
            "FromOutGate": iFromOutGate,
            "VipCode": vipCode
        }];
        if (app.PageName.toUpperCase() === 'SCANOUTYARD') 
        {
             if(messageType!=4)
             {
                 SendMessage(10/*MessageType.扫码交费*/, body, 0, "");//扫码交费  
             }
             else
             {
                 SendMessage(messageType/*MessageType.扫码交费*/, body, 0, "");//扫码交费
             } 
        }
        else
        {
             SendMessage(messageType/*MessageType.算费请求 MessageType.获取场所*/, body, 0, "");//只有4或者6  即算费请求 或 获取场所
        }
    } 
}

function startScanOutYard() {
    console.log("准备连接服务-->"+api.ApiChatUrl);
    log.info("准备连接服务-->"+api.ApiChatUrl);
    
    log.info("准备打开连接Hub2");
    try {
        util.showFullScreenLoading('请求通道车辆......'); 
        app.hadGateRecvice = false;
        app.startConnectedTime = new Date();
        
        
        if(!app.connection || !app.connection.IsConnectioned())
        {
            initConnection(); 
            app.connection.connection(api.ApiChatUrl+"/AiYardChat");
        }
        if(app.interreq==null)
        {
            app.interreq = setInterval(function () {
                if(app.connection && app.connection.IsConnectioned())
                {
                    let vipCode = "";
                    if(app.NewVip!=null)
                    {
                    vipCode = app.NewVip.member_code;
                    }
                    let YardClientId = parseInt(app.BillNo, 10);  
                    let PassId = parseInt(app.SaleId, 10); 
                    let body = [{
                        "StationId": app.StationId,
                        "StationNo": app.StationNo,
                        "StationName": app.StationName,
                        "PlateNo": YardClientId,
                        "PayCardTypeId": 0,
                        "PlateColor": PassId,
                        "OpenId": app.OpenId,
                        "ClientType": app.BrowserType,
                        "TenantId": app.TenantId,
                        "freeType": 0,
                        "freeValue": 0,
                        "PayEndTime": "",
                        "FromOutGate": "Y",
                        "VipCode": vipCode
                    }];
                    clearInterval(app.interreq);
                    app.interreq = null;
                    SendMessage(10/*MessageType.扫码交费*/, body, 0, "");//扫码交费   
                    return;
                }
            }, 500);
        }
        setTimeout(function () {
            if (!app.hadGateRecvice) {
                util.tryHideFullScreenLoading(true);
                util.showErrorToast('对不起！请求超时，请重新扫码',999999);
            }
        }, 10000);
        //五秒一次的心跳包
        if(app.interval==null)
        {
            app.interval = setInterval(function () {
                    
                let body = {
                    "PorgramVersion": "PV1.0",
                    "DataBaseVersion": "",
                    "Id": 0,
                    "PassId": 0,
                    "PassIndex": 0,
                    "Video_Ip": "",
                    "Video_Status": "",
                    "Display_Ip": "",
                    "Display_Status": ""
                }
                try
                { 
                    if(!app.connection || !app.connection.IsConnectioned())
                    {
                        console.log("掉线了，准备重新发起连接......");
                        app.connection.connection(api.ApiChatUrl+"/AiYardChat");
                    }
                }
                catch(err)
                {}
                SendMessage(0/*MessageType.心跳包*/, body, 0, "");//心跳包
            }, 5000); 
        }
    } catch (err) { //扫码失败
        util.tryHideFullScreenLoading(true);
        util.showErrorToast('对不起！连接服务器失败，请重新扫码',999999);
        //扫码失败
         
    }
}

function startNotice() { 
    try {  
        setTimeout(() => { 
            if(!app.connection || !app.connection.IsConnectioned())
            {
                let now = new Date();
                var timeSpan = Math.abs(now - app.startConnectedTime);
                if(timeSpan>9000)
                {
                    util.tryHideFullScreenLoading(true);
                    util.showErrorToast('对不起！通知超时，请重新扫码',999999);
                    return;
                }
            }
        }, 10000);  
        if(!app.connection || !app.connection.IsConnectioned())
        {
            initConnection();
            app.connection.connection(api.ApiChatUrl+"/AiYardChat");
        }
        //不需要通知到具体的客户端 
        let body = {
            "IN_ID": app.payRecordId,
            "PlateNo": app.payPlateNo,
            "INT_TIME": app.payINTime,
            "PassId": 0,
            "isRequestPass":1,
        }
        app.NoticeTimes++
        //通知客户端开闸
        SendMessage(7/*MessageType.交费成功*/, body, 0, "");//交费成功 
    } catch (err) {
        //最多通知3遍
        if (app.NoticeTimes <= 3) {
            startNotice();
        }
    }
}

function couponBill(iPlateNo) { 
    try {    
        app.startConnectedTime = new Date();
        setTimeout(() => { 
            if(!app.connection || !app.connection.IsConnectioned())
            {
                let now = new Date();
                var timeSpan = Math.abs(now - app.startConnectedTime);
                if(timeSpan>9000)
                {
                    util.tryHideFullScreenLoading(true);
                    util.showErrorToast('对不起！领券连接超时，请重新扫码',999999);
                    return;
                }
            }
        }, 10000);    
        let iOpenId = app.OpenId;
        let iClientType = 3;
        let body = { 
            "PlateNo": iPlateNo, 
            "OpenId": iOpenId,
            "ClientType": iClientType,
            "SaleId": app.SaleId,
            "BillNo": app.BillNo,/*动态码用来存时间戳*/ 
            "TenantId": app.TenantId,
        };
        SendMessage(11/*MessageType.领取停车券*/, body, 0, "");//领取停车券
    } catch (err) {
         log.error('发送领取通知异常-->'+JSON.stringify(err))
    }
}
module.exports = {  
  //以下是函数
  initConnection: initConnection,
  SendMessage: SendMessage,
  startPayNormal: startPayNormal,
  startOpenGate: startOpenGate,
  GetSationId: GetSationId,
  startScanOutYard: startScanOutYard,
  startNotice: startNotice,
  couponBill: couponBill
}